import React, { useState, useEffect } from 'react';
import {
  Modal,
  Button,
  Space,
  Typography,
  List,
  Tag,
  Card,
  Toast,
  Spin,
  Descriptions,
  Divider,
  Collapse,
  CodeHighlight,
} from '@douyinfe/semi-ui';
import { IconCode, IconFile, IconFolder, IconRefresh, IconDownload } from '@douyinfe/semi-icons';
import { menuApi, SysMenu } from '../api/menu';
import { RouteGenerator } from '../utils/routeGenerator';

const { Title, Text, Paragraph } = Typography;

interface MenuSyncToolProps {
  visible: boolean;
  onCancel: () => void;
  selectedMenuId?: number;
}

interface GeneratedFile {
  path: string;
  content: string;
  type: 'component' | 'api' | 'route';
  description: string;
}

const MenuSyncTool: React.FC<MenuSyncToolProps> = ({
  visible,
  onCancel,
  selectedMenuId,
}) => {
  const [loading, setLoading] = useState(false);
  const [menus, setMenus] = useState<SysMenu[]>([]);
  const [selectedMenu, setSelectedMenu] = useState<SysMenu | null>(null);
  const [generatedFiles, setGeneratedFiles] = useState<GeneratedFile[]>([]);
  const [activeKey, setActiveKey] = useState<string>('preview');

  useEffect(() => {
    if (visible) {
      loadMenus();
    }
  }, [visible]);

  useEffect(() => {
    if (selectedMenuId && menus.length > 0) {
      const menu = menus.find(m => m.id === selectedMenuId);
      if (menu) {
        setSelectedMenu(menu);
        generateFiles(menu);
      }
    }
  }, [selectedMenuId, menus]);

  const loadMenus = async () => {
    setLoading(true);
    try {
      const menuList = await menuApi.getMenuTree();
      setMenus(menuList);
    } catch (error) {
      console.error('加载菜单失败:', error);
      Toast.error('加载菜单失败');
    } finally {
      setLoading(false);
    }
  };

  const generateFiles = (menu: SysMenu) => {
    if (!menu.menuPath || menu.menuType !== 2) {
      Toast.warning('只能为页面类型的菜单生成文件');
      return;
    }

    const files: GeneratedFile[] = [];

    // 生成页面组件
    const componentContent = RouteGenerator.generatePageComponent(menu);
    const componentPath = RouteGenerator.getFilePath(menu.menuPath);
    files.push({
      path: componentPath,
      content: componentContent,
      type: 'component',
      description: '页面组件文件，包含完整的CRUD操作界面',
    });

    // 生成API接口
    const apiContent = RouteGenerator.generateApiTemplate(menu);
    const componentName = RouteGenerator.getComponentName(menu.menuPath);
    const apiFileName = `${componentName.toLowerCase().replace('management', '').replace('page', '')}.ts`;
    files.push({
      path: `src/api/${apiFileName}`,
      content: apiContent,
      type: 'api',
      description: 'API接口定义文件，包含所有后端接口调用方法',
    });

    // 生成路由配置
    const routeContent = RouteGenerator.generateRouteConfig([menu]);
    files.push({
      path: 'src/router/dynamicRoutes.ts',
      content: routeContent,
      type: 'route',
      description: '动态路由配置文件，需要手动集成到主路由文件中',
    });

    setGeneratedFiles(files);
  };

  const handleDownloadFile = (file: GeneratedFile) => {
    const blob = new Blob([file.content], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = file.path.split('/').pop() || 'file.txt';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    Toast.success('文件下载成功');
  };

  const handleDownloadAll = () => {
    generatedFiles.forEach(file => {
      setTimeout(() => handleDownloadFile(file), 100);
    });
  };

  const getFileIcon = (type: string) => {
    switch (type) {
      case 'component':
        return <IconFile style={{ color: '#1890ff' }} />;
      case 'api':
        return <IconCode style={{ color: '#52c41a' }} />;
      case 'route':
        return <IconFolder style={{ color: '#faad14' }} />;
      default:
        return <IconFile />;
    }
  };

  const getFileTypeTag = (type: string) => {
    switch (type) {
      case 'component':
        return <Tag color="blue" size="small">组件</Tag>;
      case 'api':
        return <Tag color="green" size="small">API</Tag>;
      case 'route':
        return <Tag color="orange" size="small">路由</Tag>;
      default:
        return <Tag size="small">文件</Tag>;
    }
  };

  return (
    <Modal
      title={
        <Space>
          <IconCode />
          菜单同步工具
        </Space>
      }
      visible={visible}
      onCancel={onCancel}
      width={1000}
      height={700}
      footer={
        <Space>
          <Button onClick={onCancel}>关闭</Button>
          {generatedFiles.length > 0 && (
            <Button
              theme="solid"
              type="primary"
              icon={<IconDownload />}
              onClick={handleDownloadAll}
            >
              下载所有文件
            </Button>
          )}
        </Space>
      }
    >
      <Spin spinning={loading}>
        {selectedMenu && (
          <Card style={{ marginBottom: 16 }}>
            <Descriptions
              data={[
                { key: '菜单名称', value: selectedMenu.menuName },
                { key: '菜单路径', value: selectedMenu.menuPath || '-' },
                { key: '菜单类型', value: selectedMenu.menuType === 1 ? '目录' : selectedMenu.menuType === 2 ? '页面' : '按钮' },
                { key: '菜单图标', value: selectedMenu.menuIcon || '-' },
                { key: '排序', value: selectedMenu.menuSort || 0 },
              ]}
              size="small"
            />
          </Card>
        )}

        {generatedFiles.length > 0 ? (
          <div>
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Title heading={5}>生成的文件 ({generatedFiles.length})</Title>
                <Button
                  size="small"
                  icon={<IconRefresh />}
                  onClick={() => selectedMenu && generateFiles(selectedMenu)}
                >
                  重新生成
                </Button>
              </Space>
            </div>

            <List
              dataSource={generatedFiles}
              renderItem={(file, index) => (
                <List.Item
                  key={index}
                  header={
                    <Space>
                      {getFileIcon(file.type)}
                      <div>
                        <Text strong>{file.path}</Text>
                        <br />
                        <Text type="tertiary" size="small">{file.description}</Text>
                      </div>
                    </Space>
                  }
                  extra={
                    <Space>
                      {getFileTypeTag(file.type)}
                      <Button
                        size="small"
                        icon={<IconDownload />}
                        onClick={() => handleDownloadFile(file)}
                      >
                        下载
                      </Button>
                    </Space>
                  }
                >
                  <Collapse
                    activeKey={activeKey === `file-${index}` ? `file-${index}` : undefined}
                    onChange={(key) => setActiveKey(key as string)}
                  >
                    <Collapse.Panel header="查看代码" itemKey={`file-${index}`}>
                      <div style={{ maxHeight: 300, overflow: 'auto' }}>
                        <CodeHighlight
                          code={file.content}
                          language={file.path.endsWith('.ts') || file.path.endsWith('.tsx') ? 'typescript' : 'javascript'}
                        />
                      </div>
                    </Collapse.Panel>
                  </Collapse>
                </List.Item>
              )}
            />

            <Divider margin="16px" />

            <Card>
              <Title heading={6}>使用说明</Title>
              <Paragraph>
                1. 下载生成的文件到对应的目录中
                <br />
                2. 根据实际业务需求调整页面组件代码
                <br />
                3. 实现对应的后端API接口
                <br />
                4. 将路由配置集成到主路由文件中
                <br />
                5. 测试页面功能是否正常
              </Paragraph>
              
              <Title heading={6}>注意事项</Title>
              <Paragraph>
                • 生成的代码仅为模板，需要根据实际业务逻辑进行调整
                <br />
                • API接口需要与后端开发人员协调实现
                <br />
                • 确保路由路径与菜单配置保持一致
                <br />
                • 页面权限控制需要与权限系统集成
              </Paragraph>
            </Card>
          </div>
        ) : (
          <Card>
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <IconCode size="large" style={{ color: '#ccc', marginBottom: 16 }} />
              <Title heading={5} style={{ color: '#999' }}>暂无生成的文件</Title>
              <Text type="tertiary">
                {selectedMenu 
                  ? '当前菜单不支持文件生成（仅支持页面类型菜单）'
                  : '请选择一个菜单来生成对应的前端文件'
                }
              </Text>
            </div>
          </Card>
        )}
      </Spin>
    </Modal>
  );
};

export default MenuSyncTool;